/*
 * @lc app=leetcode.cn id=106 lang=typescript
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

//  思路：迭代
//  同105题的思路，通过分割点与长度构建树

//  复杂度：O(n) O(1)

function buildTree(inorder: number[], postorder: number[]): TreeNode | null {
    if (!inorder.length) return null
    const len = postorder.length
    const root = new TreeNode(postorder[len - 1])
    const index = inorder.indexOf(postorder[len - 1])
    const inLeft = inorder.slice(0, index), inRight = inorder.slice(index + 1)
    const postLeft = postorder.slice(0, inLeft.length), postRight = postorder.slice(postLeft.length, len - 1)
    root.left = buildTree(inLeft, postLeft)
    root.right = buildTree(inRight, postRight)
    return root
};
// @lc code=end

import { TreeNode } from "./type"

const inorder = [9, 3, 15, 20, 7]
const postorder = [9, 15, 7, 20, 3]
console.log(TreeNode.printTree(buildTree(inorder, postorder)))
